﻿var countUploadedImages = 0;
var total = 0;
var uploadedCount = 0;

$(document).ready(function () {
    $("#btnUploadImage").change(handleUpload);

    $("#btnBack").click(handleBack);

    $("#btnDelete").click(handleDelete);

    $("#btnUpdate").click(handleUpdate);

    $(".lnkImage").click(handleLoadImage);
});

var handleLoadImage = function (e) {
    var action = "/Master/LoadAllThumnail";
    var groupId = $("#groupId").val();
    var subGroupId = $("#subGroupId").val();
    var productId = $("#productId").val();
    var param = "?groupId=" + groupId + "&subGroupId=" + subGroupId +
        "&productId=" + productId;
    $("#toPopup").removeClass("mediumSize").addClass("largeSize");
    $("#popup").removeClass("mediumSize").addClass("largeSize");
    $("#popup").attr("src", action + param);
    showPopup();
    return false;
}

var handleUpdate = function (event) {
    var product = {
        GroupId: $("#groupId").val(),
        SubGroupId: $("#subGroupId").val(),
        Id: $("#productId").val(),
        Price: $("#price").val(),
        Qty: $("#qty").val(),
        Description: $("#description").val(),
        FreeService: $("#freeService").val(),
        FeeService: $("#feeService").val()
    };

    $.ajax({
        type: "POST",
        url: "/Master/UpdateProduct",
        async: false,
        data: {
            data: JSON.stringify(product)
        },
        dataType: "json",
        success: function (data) {
            // console.log(data);
            if (data == null || data == ERROR_PAGE) {
                alert("Xóa sản phẩm đã xảy ra lỗi, hãy thử lại.");
            }
            else if (data == LOST_SESSION) {
                redirectToLogin();
            }
            else if (data == PAGE_OK) {
                $("#btnBack").click();
            }
        }
    });
}

var handleDelete = function (e) {
    if (!confirm("Bạn chắc chắn muốn xóa sản phẩm này?")) {
        return false;
    }

    var groupId = $("#groupId").val();
    var subGroupId = $("#subGroupId").val();
    var productId = $("#productId").val();
    var data = {
        groupId: groupId,
        subGroupId: subGroupId,
        productId: productId
    };

    $.ajax({
        type: "POST",
        url: "/Master/Delete",
        async: false,
        data: data,
        dataType: "json",
        success: function (data) {
            // console.log(data);
            if (data == null || data == ERROR_PAGE) {
                alert("Xóa sản phẩm đã xảy ra lỗi, hãy thử lại.");
            }
            else if (data == LOST_SESSION) {
                redirectToLogin();
            }
            else if (data == PAGE_OK) {
                $("#btnBack").click();
            }
        }
    });
}

var handleClickImage = function (e) {
    // var action = "/Master/LoadImage";
    // var param = 
    // showPopup();
    return false;
}

var handleClickRecord = function (e) {
    if ($("input").is(":focus") || $("textarea").is(":focus")) {
        return false;
    }

    if ($(this).hasClass("selected")) {
        $(this).removeClass("selected");
    }
    else {
        $(this).addClass("selected");
    }

    $(this).find("table").unbind("click");

    if ($("div.selected").length > 0) {
        $("#btnDelete").removeClass("disabled").removeAttr("disabled");
    }
    else {
        $("#btnDelete").addClass("disabled").attr("disabled", "disabled");
    }
}

var handleUpload = function (e) {

    e.preventDefault();
    e.stopPropagation();
    var fileInput = document.getElementById("btnUploadImage");

    if (fileInput.files.length == 0) {
        return;
    }

    lockScroll();
    loading();

    total = fileInput.files.length;
    uploadedCount = 0;

    for (var i = 0; i < total; i++) {

        var request = new XMLHttpRequest();

        var data = new FormData();
        data.append("file", fileInput.files[i]);
        data.append("index", "0;");

        processUpload(request, "0");

        request.open("POST", "/Master/Upload");
        request.setRequestHeader("Cache-Control", "no-cache");

        request.send(data);
    }
}

var handleBack = function () {
    var controler = "Master";
    var action = "Main";
    var goBack = $("#goBack").val();
    var arr = goBack.split(";");
    var groupId = "";
    var subGroupId = "";

    if (goBack.length >= 2) {
        groupId = arr[0];
        subGroupId = arr[1];
    }

    var param = "pageIndex=1&groupId=" + groupId + "&subGroupId=" + subGroupId;

    redirectToPage(controler, action, param);
}

/**
  * Upload image
  */
function processUpload(request, index) {
    // Create progress bar and calculating uploaded percent
    request.upload.addEventListener('progress', function (event) {
        if (event.lengthComputable) {
            var uploadPercent = Math.round((parseFloat(event.loaded / event.total) * 100)) + PERCENT;

            if (uploadPercent == UPLOADED_PERCENT) {
                uploadedCount++;

                if (uploadedCount == total) {
                    enablePage();
                }
            }
        }
    });

    request.upload.addEventListener('error', function (event) {
        uploadedCount++;

        if (uploadedCount == total) {
            enablePage();
        }
        // alert("error");
        console.log(event);
    });
}